<template>
    <div id="barChart"></div>
</template>

<script setup>
import { reactive, onMounted, watch, defineProps, getCurrentInstance } from 'vue'
/*
    柱状图数据类型： { title: 主题,xData: x轴数据, yData: y轴数据 }
*/
// --父组件数据获取并监听--
let props = defineProps(['barData', 'resizeOrNot'])
watch(() => props.barData, () => {
    echartsInit()
}, { deep: true })
watch(() => props.resizeOrNot, () => {
    myChart.resize()
}, { deep: true })
let myChart = reactive({}) // echarts实例载体
const { proxy } = getCurrentInstance()
// 初始化图表
let echartsInit = () => {
    myChart = proxy.$echarts.init(document.getElementById('barChart'))
    let option = {
        title: {
            text: props.barData.title,
            textStyle: {
                color: '#fff',
                fontSize: 25,
                fontWeight: 800,
                fontFamily: 'Microsoft YaHei',
                textBorderColor: '#191919',
                textBorderWidth: 5,
            },
            left: 'center',
            top: '10',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: (params) => {
                return `<h4>${params[0].name}</h4><span class="tooltipPoint"></span>销量：${params[0].data.value}</br><span class="tooltipPoint"></span>售价：${params[0].data.price}`
            },
            backgroundColor: '#191919bb',
            borderColor: '#191919aa',
            borderWidth: 2,
            textStyle: {
                color: '#fff'
            },
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: props.barData.xData,
                axisTick: {
                    alignWithLabel: true
                },
                axisLabel: {
                    rotate: 20, // x轴倾斜
                    interval: 0, // 显示全部x轴数据
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                data: props.barData.yData,
            }
        ],
        series: [
            {
                name: '销量',
                type: 'bar',
                barWidth: '60%',
                data: props.barData.yData,
                itemStyle: {
                    color: '#191919'
                }
            },
        ]
    }
    myChart.clear() // 清空实例，但似乎无效(无法消除警告)
    myChart.setOption(option)
}
onMounted(() => {
    echartsInit() // 初始化图表
})
</script>

<style lang="scss" scoped>
#barChart {
    height: 100%;
    width: 100%;
}

::v-deep .tooltipPoint {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #191919;
    display: inline-block;
    margin-right: 1rem;
}
</style>